package com.nowcoder.community.service.impl;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @author cjh
 * @date 2023/2/8 - 16:30
 */
@Service
public class DataService {
    @Autowired
    private RedisTemplate redisTemplate;
//    年月日
    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    /**
     * 将指定ip计入uv
     */
    public void recordUV(String ip){
        String redisKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(redisKey,ip);
    }

    /**
     * 统计指定日期范围得UV
     */
    public long calculateUV( Date start, Date end){
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
//        整理该日期范围内的key
        ArrayList<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(key);
            calendar.add(Calendar.DATE,1);
        }

//        合并key
        String redisKey = RedisKeyUtil.getUVKey(df.format(start), df.format(end));
        redisTemplate.opsForHyperLogLog().union(redisKey,keyList.toArray());

//        返回统计的结果
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }

    /**
     * 将指定用户计入DAU
     */
    public void recordDAU(int userId){
        String redisKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey,userId,true);
    }

    /**
     * 统计指定日期范围内的DAU
     */

    public long calculateDAU(Date start,Date end){
        if (start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
//        整理该日期范围内的key
        ArrayList<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes(StandardCharsets.UTF_8));
            calendar.add(Calendar.DATE,1);
        }
//        进行or运算
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtil.getDAUKey(df.format(start),df.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,redisKey.getBytes(StandardCharsets.UTF_8)
//                        这里是声明需要返回的类型  带下不用管 因为底层会处理
                ,keyList.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes(StandardCharsets.UTF_8));
            }
        });
    }

}
